package com.gzsxy.sso.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.sso.common.dto.request.FunctionRequest;
import com.gzsxy.sso.common.exception.impl.BusinessException;
import com.gzsxy.sso.common.exception.impl.CustomAssert;
import com.gzsxy.sso.common.result.ResultCodeEnum;
import com.gzsxy.sso.core.dao.FunctionMapper;
import com.gzsxy.sso.core.dao.MenuMapper;
import com.gzsxy.sso.core.entity.Function;
import com.gzsxy.sso.core.entity.vo.FunctionQueryVo;
import com.gzsxy.sso.core.model.SessionUser;
import com.gzsxy.sso.core.service.FunctionService;
import com.gzsxy.sso.core.utils.SessionUserUtil;
import com.gzsxy.sso.core.utils.ValidateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author xiaolong
 * @version 1.0
 * @description: 功能管理
 * @date 2021/11/18 11:24
 */
@Service
public class FunctionServiceImpl extends ServiceImpl<FunctionMapper, Function> implements FunctionService {


    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private FunctionMapper functionMapper;




    /**
     * @description: 获取所以功能列表
     * @param
     * @return
     */
    @Override
    public IPage<Function> getAllFunction(Page<Function> pageParam, FunctionQueryVo functionQueryVo) {
        //显示分页查询列表
        // 1.排序：按照sort字段排序
        QueryWrapper<Function> queryWrapper = new QueryWrapper<Function>();
        queryWrapper.orderByDesc("order_id");//通过sort字段进行升序
        queryWrapper.eq("is_deleted",0);

        if (ObjectUtils.isEmpty(functionQueryVo)){
             return baseMapper.selectPage(pageParam,queryWrapper);
        }
        String id = functionQueryVo.getId();
        String name = functionQueryVo.getName();
        String appId = functionQueryVo.getAppId();

        if (StringUtils.isNotEmpty(id)){
            queryWrapper.eq("id",id);
        }
        if (StringUtils.isNotEmpty(name)){
            queryWrapper.like("name",name);
        }
        if (StringUtils.isNotEmpty(appId)){
            queryWrapper.eq("app_id",appId);
        }
        return baseMapper.selectPage(pageParam,queryWrapper);
    }




    /**
     * @description: 添加功能
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addFunction(FunctionRequest functionRequest) {
        LambdaQueryWrapper<Function> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Function::getName, functionRequest.getName());
        //避免不同应用出现重复不可用现象
        wrapper.eq(Function::getAppId,functionRequest.getAppId());
        Function function = baseMapper.selectOne(wrapper);
        //唯一功能名校验
        CustomAssert.notTrue(ObjectUtils.isEmpty(function),ResultCodeEnum.FUNCTION_NAME_EXIST.getMessage(),ResultCodeEnum.FUNCTION_NAME_EXIST.getCode());
        Function function1 = new Function();
        BeanUtils.copyProperties(functionRequest,function1);
        //设置标识
        String pinYinHeadChar = com.gzsxy.sso.common.utils.StringUtils.getPinYinHeadChar(functionRequest.getName());
        function1.setMark(pinYinHeadChar);
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        function1.setAddUser(sessionUser.getUserName());
//        function1.setUpdateUser(sessionUser.getUserName());
        baseMapper.insert(function1);
    }



    /**
     * @description: 根据id查询功能
     * @param
     * @return
     */
    @Override
    public Function selectById(String functionId) {
        return baseMapper.selectById(functionId);
    }


    /**
     * @description: 编辑功能
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateFunction(FunctionRequest functionRequest) {
        Function function = baseMapper.selectById(functionRequest.getId());
        //该功能不存在
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(function),ResultCodeEnum.FUNCTION_NOT_FOUND.getMessage(),ResultCodeEnum.FUNCTION_NOT_FOUND.getCode());
        Function function1 = new Function();
        BeanUtils.copyProperties(functionRequest,function1);

        //修改了功能名
        if (!function.getName().equals(functionRequest.getName())){
            //功能名称唯一性校验
            ValidateUtil.assertUnique(functionMapper::existByFuncName,functionRequest.getAppId(),functionRequest.getName(),ResultCodeEnum.MENU_NAME_EXIST.getMessage());
            String pinYinHeadChar = com.gzsxy.sso.common.utils.StringUtils.getPinYinHeadChar(functionRequest.getName());
            function1.setMark(pinYinHeadChar);
        }
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        function1.setUpdateUser(sessionUser.getUserName());
        baseMapper.updateById(function1);
    }


    /**
     * @description: 删除功能
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String functionId,Boolean isConform) {
        Function function = baseMapper.selectById(functionId);
        //功能名不存在或已删除
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(function),ResultCodeEnum.FUNCTION_NOT_FOUND.getMessage(),ResultCodeEnum.FUNCTION_NOT_FOUND.getCode());
        if (menuMapper.existByFuncId(functionId)){
            if (!isConform){
                throw new BusinessException(ResultCodeEnum.MENU_FUNCTION_EXIST.getMessage());
            }
            //解除关联(但不删除)
            menuMapper.clearFuncId(functionId);
        }
        baseMapper.deleteById(functionId);
    }

    /**
     * @description: 通过appId查询功能列表
     * @param appId 应用id
     * @return
     */
    @Override
    public List<Function> selectFunByAppId(String appId) {
        LambdaQueryWrapper<Function> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Function::getAppId,appId);
        List<Function> list = functionMapper.selectList(wrapper);
        return list;
    }
}
